package mrpheu.demo.client.tcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

public class ChatTCPClientThread implements Runnable {

    private Socket socket = null;
    private DataInputStream streamIn = null;
    private Integer id = null;
    
    private boolean off = false;

    public ChatTCPClientThread(Socket socket) {
        this.socket = socket;
    }

    public void open() {
        if(this.socket != null) {
            System.out.println("Get inputstream...");
            try {
                this.streamIn = new DataInputStream(this.socket.getInputStream());
                String strId = this.streamIn.readUTF();
                this.id = Integer.parseInt(strId);
            } catch (IOException e) {
                System.out.println("Socket null!");
                this.off = true;
                return;
            }
        } else {
            this.off = true;
        }
    }

    public void process() {
        System.out.println("Client process...");
        String line = "";
        while (!this.off) {
            try {
                System.out.println("Waiting data...");
                line = this.streamIn.readUTF();
                System.out.println(line);
                this.off = line.equals(".bye");
            } catch (IOException e) {
                this.off = true;
            }
        }
        this.close();
    }

    public void close() {
        try {
            if (this.streamIn != null) {
                this.streamIn.close();
            }
            if  (this.socket != null) {
                this.socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        System.out.println("Listener'client starting...");
        this.open();
        this.process();
    }

    
    public Integer getId() {
        return id;
    }

    
    public void setId(Integer id) {
        this.id = id;
    }
    
    

}
